﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DynamicDNS.Model;
using NDatabase;

namespace DynamicDNS
{
    public class ConfigurationContext : IDbContext
    {
        const string DbFilename = "DynamicDNS.db";

        private Configuration Initize()
        {
            var config = new Configuration();
            config.StartType = StartType.Automatic;
            config.Records = new List<Record>();
            return config;
        }

        private void Reset()
        {
            OdbFactory.Delete(DbFilename);
        }

        public Configuration Get()
        {
            Configuration config;
            try
            {
                using (var odb = OdbFactory.Open(DbFilename))
                {
                    IList<Configuration> query = odb.Query<Configuration>().Execute<Configuration>().ToList();
                    config = query[0];
                }
            }
            catch
            {
                config = Initize();
                Save(config, true);
            }
            return config;
        }
        public Configuration Save(Configuration config)
        {
            return Save(config, false);
        }
        public Configuration Save(Configuration config, bool forced)
        {
            using (var odb = OdbFactory.Open(DbFilename))
            {
                if (forced)
                    odb.Store(config);
                else
                {
                    IList<Configuration> list = odb.Query<Configuration>().Execute<Configuration>().ToList();
                    var original = list[0];
                    ConfigCopy(ref original, config);
                    odb.Store(original);
                }
                return config;
            }
        }
        private void ConfigCopy(ref Configuration original, Configuration purpose)
        {
            original.StartType = purpose.StartType;
            original.Records = purpose.Records;
        }
    }
}
